Self-Driving Car Engineer Nanodegree

Project: Finding Lane Lines on the Road


In this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really just a series of images). Check out the video clip "raw-lines-example.mp4" (also contained in this repository) to see what the output should look like after using the helper functions below.

Once you have a result that looks roughly like "raw-lines-example.mp4", you'll need to get creative and try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video "P1_example.mp4". Ultimately, you would like to draw just one line for the left side of the lane, and one for the right.

In addition to implementing code, there is a brief writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing both the code in the Ipython notebook and the writeup template will cover all of the rubric points for this project.


Let's have a look at our first image called 'test_images/solidWhiteRight.jpg'. Run the 2 cells below (hit Shift-Enter or the "play" button above) to display the image.

Note: If, at any point, you encounter frozen display windows or other confounding issues, you can always start again with a clean slate by going to the "Kernel" menu above and selecting "Restart & Clear Output".


The tools you have are color selection, region of interest selection, grayscaling, Gaussian smoothing, Canny Edge Detection and Hough Tranform line detection. You are also free to explore and try other techniques that were not presented in the lesson. Your goal is piece together a pipeline to detect the line segments in the image, then average/extrapolate them and draw them onto the image for display (as below). Once you have a working pipeline, try it out on the video stream below.


Combined Image

Your output should look something like this (above) after detecting line segments using the helper functions below

Combined Image

Your goal is to connect/average/extrapolate line segments to get output like this

Run the cell below to import some packages. If you get an import error for a package you've already installed, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, consult the forums for more troubleshooting tips.

Import Packages

In [1]:
#importing some useful packages
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
%matplotlib inline

Read in an Image

In [2]:
#reading in an image
image = mpimg.imread('test_images/solidWhiteRight.jpg')

#printing out some stats and plotting
print('This image is:', type(image), 'with dimensions:', image.shape)
plt.imshow(image)  # if you wanted to show a single color channel image called 'gray', for example, call as plt.imshow(gray, cmap='gray')
This image is: <class 'numpy.ndarray'> with dimensions: (540, 960, 3)
Out[2]:
<matplotlib.image.AxesImage at 0x2193eca3e80>

Ideas for Lane Detection Pipeline

Some OpenCV functions (beyond those introduced in the lesson) that might be useful for this project are:

cv2.inRange() for color selection
cv2.fillPoly() for regions selection
cv2.line() to draw lines on an image given endpoints
cv2.addWeighted() to coadd / overlay two images cv2.cvtColor() to grayscale or change color cv2.imwrite() to output images to file
cv2.bitwise_and() to apply a mask to an image

Check out the OpenCV documentation to learn about these and discover even more awesome functionality!

Helper Functions

Below are some helper functions to help get you started. They should look familiar from the lesson!

In [3]:
import math

def grayscale(img):
    """Applies the Grayscale transform
    This will return an image with only one color channel
    but NOTE: to see the returned image as grayscale
    (assuming your grayscaled image is called 'gray')
    you should call plt.imshow(gray, cmap='gray')"""
    return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    # Or use BGR2GRAY if you read an image with cv2.imread()
    # return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
def canny(img, low_threshold, high_threshold):
    """Applies the Canny transform"""
    return cv2.Canny(img, low_threshold, high_threshold)

def gaussian_blur(img, kernel_size):
    """Applies a Gaussian Noise kernel"""
    return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)

def region_of_interest(img, vertices):
    """
    Applies an image mask.
    
    Only keeps the region of the image defined by the polygon
    formed from `vertices`. The rest of the image is set to black.
    """
    #defining a blank mask to start with
    mask = np.zeros_like(img)   
    
    #defining a 3 channel or 1 channel color to fill the mask with depending on the input image
    if len(img.shape) > 2:
        channel_count = img.shape[2]  # i.e. 3 or 4 depending on your image
        ignore_mask_color = (255,) * channel_count
    else:
        ignore_mask_color = 255
        
    #filling pixels inside the polygon defined by "vertices" with the fill color    
    cv2.fillPoly(mask, vertices, ignore_mask_color)
    
    #returning the image only where mask pixels are nonzero
    masked_image = cv2.bitwise_and(img, mask)
    return masked_image

def draw_lines(img, lines, vertices, extrapolate_YN, color=[255, 0, 0], thickness=8):
    """
    NOTE: this is the function you might want to use as a starting point once you want to 
    average/extrapolate the line segments you detect to map out the full
    extent of the lane (going from the result shown in raw-lines-example.mp4
    to that shown in P1_example.mp4).  
    
    Think about things like separating line segments by their 
    slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left
    line vs. the right line.  Then, you can average the position of each of 
    the lines and extrapolate to the top and bottom of the lane.
    
    This function draws `lines` with `color` and `thickness`.    
    Lines are drawn on the image inplace (mutates the image).
    If you want to make the lines semi-transparent, think about combining
    this function with the weighted_img() function below
    """
    left_lines = []
    right_lines = []
    for line in lines:
        for x1,y1,x2,y2 in line:
            
            if (x2-x1) == 0 or (y2-y1) == 0:
                continue
            
            
            slope = (y2-y1)/(x2-x1)
            if slope > 0.5:
                #If slope is negative, lines are in left side of the road
                left_lines.append(line)
            elif slope < -0.5:
                right_lines.append(line)
            
            cv2.line(img, (x1, y1), (x2, y2), color, thickness)
            
    if extrapolate_YN is True:
        img = extrapolate(img, left_lines, vertices ,color, thickness) 
        img = extrapolate(img, right_lines, vertices, color, thickness) 
            
    return img


def extrapolate(img, lines, vertices, color=[255, 0, 0], thickness=2):
    from scipy import stats
    xc = []
    yc = []
    for line in lines:
        for x1, y1, x2, y2 in line:
            xc.append(x1)
            xc.append(x2)
            yc.append(y1)
            yc.append(y2)
                
    if len(xc) > 0:
        slope, intercept, _,_,_ = stats.linregress(xc, yc)
        
        if slope!=0:
            bottom_y = img.shape[0]
            # Equation of the line is y = mx+b, hence x = (y - b)/a
            bottom_x = (bottom_y - intercept) / slope
            
            top_y = vertices[0][1][1]
            top_x = (top_y - intercept) / slope
        
            extrapolated_lines  = [[[int(bottom_x), int(bottom_y), int(top_x), int(top_y)]]]
    
        for line in extrapolated_lines:
            for x1,y1,x2,y2 in line:
                cv2.line(img, (x1, y1), (x2, y2), color, thickness)
    
    return img
    
    

def hough_lines(img,original_img, rho, theta, threshold, min_line_len, max_line_gap, vertices, extrapolate_YN = False):
    """
    `img` should be the output of a Canny transform.
        
    Returns an image with hough lines drawn.
    """
    lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)
    #line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)
    orig_img = np.copy(original_img)
    #draw_lines(line_img, lines)
    draw_lines(orig_img, lines, vertices, extrapolate_YN)
    #return line_img
    
    weighted_image = weighted_img(orig_img, original_img)
    return weighted_image

# Python 3 has support for cool math symbols.

def weighted_img(img, initial_img, α=0.7, β=0.5, λ=0.):
    """
    `img` is the output of the hough_lines(), An image with lines drawn on it.
    Should be a blank image (all black) with lines drawn on it.
    
    `initial_img` should be the image before any processing.
    
    The result image is computed as follows:
    
    initial_img * α + img * β + λ
    NOTE: initial_img and img must be the same shape!
    """
    return cv2.addWeighted(initial_img, α, img, β, λ)

Test Images

Build your pipeline to work on the images in the directory "test_images"
You should make sure your pipeline works well on these images before you try the videos.

In [4]:
import os
all_image_names = ["test_images/" + image_name for image_name in os.listdir("test_images/")]

image1 = mpimg.imread(all_image_names[0])
plt.imshow(image1)
Out[4]:
<matplotlib.image.AxesImage at 0x2193eef7ac8>

Pipe Line Construction

Pipeline is constructed using the following steps.

  1. Grayscale Conversion: Transform an image from BGR to Gray-scale format by using cvtColor function.

  2. Gaussian Blur: Use Gaussian smoothing to suppress noise and spurious gradients.

  3. Canny Edge Detection: Detect edges using OpenCV's cv2.Canny to detect edges in the image. This API requires Low and High thresholds for detecting strong edges above the higher threshold and reject pixels below the lower threshold.

    • In this usecase, Low threshold = 70 and High threhold = 210 worked well.
    • Kernel size of 5 was used to Gaussian Blur.
  4. Capture Region of Interest: Filter out unnecessary element from the image and retain an area which contains the lane projection. This can be done defining a poly-fit as our region of interest and mask the original image with the detected edges.

  5. Hough Lines: To find the lines in an image.

    • To detect lines, we work on the masked edges and feed it to cv2.HoughLinesP API.
    • The API will return the lines by end points (x1,y1,x2,y2) of all line segments detected by the Hough transform operation.
  6. Draw Lines: After the lines are detected using HoughLinesP, these lines are overlayed on the original image. This is a very key step to differentiate between Left vs Right lanes. I used the following steps:

    • Lane lines are broken and can either be on the left or right side of the road.
    • Made use of the line end points given by HoughLinesP to calculate the slope.
    • In this context, the origin of the image is on top left and the image space grows vertically down on y-axis and horizontally right on x-axis.
  7. Extrapolate Lines: Lines are extrapolated to run the full length of the visible lane based on the line segments identified with the Hough Transform.

    • scipy library in python provides a very good implementation to calculate a least-squares regression for two sets of measurements.
    • For each pair of points calculate the slope and intercept.
    • Use slope and intercept to regress points that connect two broken lanes. Draw lines on the main image using cv2.line feeding these regressed points as inputs.
  8. Test on Videos: Apply the result of the algorithm to a Video stream.

Canny Edge Detection

API below does Canny edge detection. Parameters are:

  1. image: image that is read using imread
  2. gaussian_kernel_size : Gaussian smoothing which is any odd number. A larger kernel_size implies averaging, or smoothing, over a larger area.
  3. low_threshold: Reject pixels below the low_threshold
  4. high_threshold: Detect strong edges (strong gradient) pixels above the high_threshold.
In [5]:
def canny_egde_detection(image, gaussian_kernel_size, low_threshold, high_threshold):
    # Read in and grayscale the image    
    gray = grayscale(image)
    blur_gray = gaussian_blur(gray, gaussian_kernel_size)
    edges = canny(blur_gray, low_threshold, high_threshold)
    return edges
  1. Specify parameters (gaussian_kernel_size, low_threshold and high_threshold.
  2. Vertices determine region of interest. Vertices is a set of 4 points which form a polygon. The region of interest will be only the area of points specified by this polygon.
In [6]:
# Define a kernel size and apply Gaussian smoothing
gaussian_kernel_size = 5

# Define parameters for Canny edge detection 
low_threshold = 70
high_threshold = 210

#define vertices for the polygon and get masked edges
im_shape = image.shape
img_width = im_shape[1]
img_height = im_shape[0]
vertices = np.array([[(140, img_height), (430, 320), (530, 320),(img_width, img_height)]], np.int32)

Test on given set of Images

Images on the left below are the ones where edges are detected.
Images on the right is the region of interest where only the projection of lanes is captures. We'll work on these images to detect and overlay lines.

In [7]:
all_images = [mpimg.imread(image_name) for image_name in all_image_names]

for i,image in enumerate(all_images):
    
    fig = plt.figure(figsize=(25, 25))
    
    #ax1 = fig.add_subplot(1,3,1)
    #plt.title(all_image_names[i][len('test_images/'):]) 
    #ax1.imshow(image)   
    
    
    edges = canny_egde_detection(image, gaussian_kernel_size, low_threshold, high_threshold)
    ax1 = fig.add_subplot(1,2,1)
    plt.title(all_image_names[i][len('test_images/'):])  
    ax1.imshow(edges,cmap='Greys_r')    
    
    masked_image = region_of_interest(edges, vertices)    
    ax2 = fig.add_subplot(1,2,2)
    plt.title(all_image_names[i][len('test_images/'):])  
    ax2.imshow(masked_image,cmap='Greys_r')
    
    
In [8]:
edge_detected_images = [canny_egde_detection(image, gaussian_kernel_size, low_threshold, high_threshold) for image in all_images]
masked_images = [region_of_interest(edges, vertices)  for edges in edge_detected_images]

Hough Transformation

Use Hough lines API to detect lines on the masked images (with only the region of interest).
This API internally

+ Calls draw_lines() to draw detected lines on Original image. 
+ Calls extrapolate() to extrapolate to join full length of the visible lanes.

Parameters used:

  1. img: Masked image with Region of interest
  2. original_img: Original Image to overlay the detected lines
  3. rho: Distance resolution in pixels of the Hough grid
  4. theta: Angular resolution in radians of the Hough grid
  5. threshold: Minimum number of votes (intersections in Hough grid cell)
  6. min_line_length: Minimum number of pixels making up a line
  7. max_line_gap: Maximum gap in pixels between connectable line segments
  8. vertices: Polygon with points capturing region of interest
  9. extrapolate_YN: If True, Lines are extrapolated to run the full length of the visible lane based on the line segments identified with the Hough Transform. Default False.

Images on the left are Original Images.
Images on the right are Overlayed with detected Lane markings using Hough Transform.

In [9]:
# Define the Hough transform parameters
rho = 2 # distance resolution in pixels of the Hough grid
theta = np.pi/180 # angular resolution in radians of the Hough grid
threshold = 50  # minimum number of votes (intersections in Hough grid cell)
min_line_length = 120 #minimum number of pixels making up a line
max_line_gap = 100  # maximum gap in pixels between connectable line segments

final_image = hough_lines(masked_images[1],all_images[1], rho, theta, threshold, min_line_length, max_line_gap, vertices) 
fig = plt.figure(figsize=(25, 25))
    
ax1 = fig.add_subplot(1,2,1)
plt.title(all_image_names[0][len('test_images/'):]) 
ax1.imshow(all_images[1])   
    
ax1 = fig.add_subplot(1,2,2)
plt.title(all_image_names[1][len('test_images/'):])  
ax1.imshow(final_image)   
Out[9]:
<matplotlib.image.AxesImage at 0x219413fe908>

Test run on All Images

In [10]:
final_images = [hough_lines(masked_images[i],all_images[i], rho, theta, threshold, min_line_length, max_line_gap, vertices)                 
                for i in range(len(masked_images)) ]
In [11]:
for i,image in enumerate(final_images):
    
    fig = plt.figure(figsize=(25, 25))
    
    ax1 = fig.add_subplot(1,2,1)
    plt.title(all_image_names[i][len('test_images/'):]) 
    ax1.imshow(all_images[i])   
    
    ax1 = fig.add_subplot(1,2,2)
    plt.title(all_image_names[i][len('test_images/'):])  
    ax1.imshow(image)    
    
    

Test on Videos

You know what's cooler than drawing lanes over images? Drawing lanes over video!

We can test our solution on two provided videos:

solidWhiteRight.mp4

solidYellowLeft.mp4

Note: if you get an import error when you run the next cell, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, consult the forums for more troubleshooting tips.

If you get an error that looks like this:

NeedDownloadError: Need ffmpeg exe. 
You can download it by calling: 
imageio.plugins.ffmpeg.download()

Follow the instructions in the error message and check out this forum post for more troubleshooting tips across operating systems.

In [12]:
# Import everything needed to edit/save/watch video clips
from moviepy.editor import VideoFileClip
from IPython.display import HTML

Put things together - process_image()

Process_image function below is used to simply piece together all the methods we used to built the pipeline

In [13]:
def process_image(image):
    # NOTE: The output you return should be a color image (3 channel) for processing video below
    # TODO: put your pipeline here,
    # you should return the final output (image where lines are drawn on lanes)
    edges = canny_egde_detection(image, gaussian_kernel_size, low_threshold, high_threshold)
    masked_image = region_of_interest(edges, vertices)    
    result = hough_lines(masked_image,image, rho, theta, threshold, min_line_length, max_line_gap, vertices)
    
    return result

Use Extrapolate to Join Lanes

The below function is similar to process_image() but used extrapolate_YN = True while calling hough_lines API. Result is a line which runs the full length of the visible lane based on the line segments identified using Hough Transform.

In [14]:
def process_image_extrapolate(image):
    # NOTE: The output you return should be a color image (3 channel) for processing video below
    # TODO: put your pipeline here,
    # you should return the final output (image where lines are drawn on lanes)
    edges = canny_egde_detection(image, gaussian_kernel_size, low_threshold, high_threshold)
    masked_image = region_of_interest(edges, vertices)    
    result = hough_lines(masked_image,image, rho, theta, threshold, min_line_length, max_line_gap, vertices, extrapolate_YN = True)
    
    return result

Test extrapolation on a single Image

Image on the right is extrapolated which joins all the lane markings on the right using a RED overlay.

In [15]:
lines_image = process_image(all_images[5])
lines_extrapolated_image = process_image_extrapolate(all_images[5])

fig = plt.figure(figsize=(25, 25))
    
ax1 = fig.add_subplot(1,2,1)
ax1.imshow(lines_image)   
    
ax1 = fig.add_subplot(1,2,2)
ax1.imshow(lines_extrapolated_image)  
Out[15]:
<matplotlib.image.AxesImage at 0x219421de860>

Let's try the one with the solid white lane on the right first ...

Test extrapolation on a solidWhiteRight Video

In [16]:
white_output = 'test_videos_output/solidWhiteRight.mp4'
## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video
## To do so add .subclip(start_second,end_second) to the end of the line below
## Where start_second and end_second are integer values representing the start and end of the subclip
## You may also uncomment the following line for a subclip of the first 5 seconds
##clip1 = VideoFileClip("test_videos/solidWhiteRight.mp4").subclip(0,5)
clip1 = VideoFileClip("test_videos/solidWhiteRight.mp4")
white_clip = clip1.fl_image(process_image_extrapolate) #NOTE: this function expects color images!!
%time white_clip.write_videofile(white_output, audio=False)
[MoviePy] >>>> Building video test_videos_output/solidWhiteRight.mp4
[MoviePy] Writing video test_videos_output/solidWhiteRight.mp4
100%|██████████████████████████████████████████████████████████████████████████████▋| 221/222 [00:02<00:00, 104.56it/s]
[MoviePy] Done.
[MoviePy] >>>> Video ready: test_videos_output/solidWhiteRight.mp4 

Wall time: 2.44 s

Play the video inline, or if you prefer find the video in your filesystem (should be in the same directory) and play it in your video player of choice.

In [18]:
HTML("""
<video width="960" height="540" controls>
  <source src="{0}">
</video>
""".format(white_output))
Out[18]:

Improve the draw_lines() function

At this point, if you were successful with making the pipeline and tuning parameters, you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)? Think about defining a line to run the full length of the visible lane based on the line segments you identified with the Hough Transform. As mentioned previously, try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video "P1_example.mp4".

Go back and modify your draw_lines function accordingly and try re-running your pipeline. The new output should draw a single, solid line over the left lane line and a single, solid line over the right lane line. The lines should start from the bottom of the image and extend out to the top of the region of interest.

Now for the one with the solid yellow lane on the left. This one's more tricky!

Test extrapolation on a solidYellowLeft Video

Isolate Yellow lines using HSL color space. (Convert the image into HSL and obtain YELLO color low and high ranges).

In [19]:
def yellow_to_white(image):
        
    yellow_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    yellow_high_range = np.array([35, 200, 255]) 
    yellow_low_range = np.array([15, 40, 120]) 
    
    yr = cv2.inRange(yellow_hsv, yellow_low_range, yellow_high_range)
    yr_rgb = cv2.cvtColor(yr, cv2.COLOR_GRAY2RGB)
    
    yellow_to_white_image = weighted_img(yr_rgb, image, α=1, β=1, λ=0.)
    return yellow_to_white_image

    
def process_image_extrapolate_y(image):
    # NOTE: The output you return should be a color image (3 channel) for processing video below
    # TODO: put your pipeline here,
    # you should return the final output (image where lines are drawn on lanes)
    yellow_to_white_image = yellow_to_white(image)
    edges = canny_egde_detection(yellow_to_white_image, gaussian_kernel_size, low_threshold, high_threshold)
    masked_image = region_of_interest(edges, vertices)    
    result = hough_lines(masked_image,image, rho, theta, threshold, min_line_length, max_line_gap, vertices, extrapolate_YN = True)
    
    return result    
In [20]:
yellow_output = 'test_videos_output/solidYellowLeft.mp4'
## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video
## To do so add .subclip(start_second,end_second) to the end of the line below
## Where start_second and end_second are integer values representing the start and end of the subclip
## You may also uncomment the following line for a subclip of the first 5 seconds
##clip2 = VideoFileClip('test_videos/solidYellowLeft.mp4').subclip(0,5)
clip2 = VideoFileClip('test_videos/solidYellowLeft.mp4')
yellow_clip = clip2.fl_image(process_image_extrapolate_y)
%time yellow_clip.write_videofile(yellow_output, audio=False)
[MoviePy] >>>> Building video test_videos_output/solidYellowLeft.mp4
[MoviePy] Writing video test_videos_output/solidYellowLeft.mp4
100%|███████████████████████████████████████████████████████████████████████████████▉| 681/682 [00:08<00:00, 79.19it/s]
[MoviePy] Done.
[MoviePy] >>>> Video ready: test_videos_output/solidYellowLeft.mp4 

Wall time: 8.92 s
In [21]:
HTML("""
<video width="960" height="540" controls>
  <source src="{0}">
</video>
""".format(yellow_output))
Out[21]:

Writeup and Submission

If you're satisfied with your video outputs, it's time to make the report writeup in a pdf or markdown file. Once you have this Ipython notebook ready along with the writeup, it's time to submit for review! Here is a link to the writeup template file.

Optional Challenge

Try your lane finding pipeline on the video below. Does it still work? Can you figure out a way to make it more robust? If you're up for the challenge, modify your pipeline so it works with this video and submit it along with the rest of your project!

In [22]:
#clip3.reader.close()
#clip3.audio.reader.close_proc()
challenge_output = 'test_videos_output/challenge.mp4'
## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video
## To do so add .subclip(start_second,end_second) to the end of the line below
## Where start_second and end_second are integer values representing the start and end of the subclip
## You may also uncomment the following line for a subclip of the first 5 seconds
##clip3 = VideoFileClip('test_videos/challenge.mp4').subclip(0,5)
clip3 = VideoFileClip('test_videos/challenge.mp4')
challenge_clip = clip3.fl_image(process_image_extrapolate_y)
%time challenge_clip.write_videofile(challenge_output, audio=False)
[MoviePy] >>>> Building video test_videos_output/challenge.mp4
[MoviePy] Writing video test_videos_output/challenge.mp4
100%|████████████████████████████████████████████████████████████████████████████████| 251/251 [00:06<00:00, 40.45it/s]
[MoviePy] Done.
[MoviePy] >>>> Video ready: test_videos_output/challenge.mp4 

Wall time: 6.83 s
In [23]:
HTML("""
<video width="960" height="540" controls>
  <source src="{0}">
</video>
""".format(challenge_output))
Out[23]:
In [ ]:
 
In [ ]: